/**
 * 
 */
package com.alphasystem.commerce.common.model;

import static com.alphasystem.commerce.common.util.HashCodeUtil.hash;
import static org.apache.commons.lang.StringUtils.isBlank;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;

/**
 * @author Farhan Syed Ali
 * 
 */
@MappedSuperclass
public class AbstractEntity implements Serializable, Comparable<AbstractEntity> {

	private static final long serialVersionUID = 4337106571129718564L;

	public static final String TEMP_ID = "__UNKNOWN__";

	protected String id;

	protected int version;

	public AbstractEntity() {
		this(TEMP_ID);
	}

	public AbstractEntity(String id) {
		setId(id);
	}

	@Override
	public int compareTo(AbstractEntity o) {
		return (o == null) ? 1 : id.compareTo(o.getId());
	}

	@Override
	public boolean equals(Object obj) {
		if (obj != null && obj instanceof AbstractEntity) {
			AbstractEntity other = (AbstractEntity) obj;
			return id.equals(other.getId());
		}
		return false;
	}

	@Id
	@Column(name = "ID", length = 40)
	public String getId() {
		return id;
	}

	@Version
	public int getVersion() {
		return version;
	}

	@Override
	public int hashCode() {
		return hash(id);
	}

	public void setId(String id) {
		if (isBlank(id)) {
			id = TEMP_ID;
		}
		this.id = id;
	}

	public void setVersion(int version) {
		this.version = version;
	}

	@Override
	public String toString() {
		return id;
	}

}
